//
//  CircleStrokeView.m
//  CircleView
//
//  Created by CPX on 2018/10/29.
//  Copyright © 2018 LYCoder. All rights reserved.
//

//****本类所有角度均是弧度数///利用大量的三角函数、圆的数学知识处理。（suggest not trying to mofity）

#import "CircleStrokeView.h"
#define kBorderWith 4
#define image_width 40

@interface CircleStrokeView ()
<UIGestureRecognizerDelegate>
{
    UIView * gestureView;//专门处理手势的view 透明色不可见
    
    CGFloat _radius_circle;//圆弧半径
    CGPoint _center_circle;//圆心点
    CGRect rect_circle;//圆形位置
    UIEdgeInsets edgeInsets_circle;//圆形左跟上偏移位置
    
    CGFloat angle_average_image;//一个念珠图所占的弧度
    BOOL success_move;//是否成功移动到下个位置、、如果滑动结束没有超过规定距离则为NO 、超过则为YES 、然后刷新球体位置
    BOOL move_direction_right;//是否向右滑动
    
    
  __block  CGFloat current_percent;//当前滑动percent
    
}
@property (nonatomic,strong)NSMutableArray <UIImageView *> * beadImages;//念珠图数组
@property (nonatomic,strong)NSMutableArray  * beadAngles;//念珠角度数组

@end

@implementation CircleStrokeView
- (NSMutableArray<UIImageView * > *)beadImages{
    if(!_beadImages){
        _beadImages = [NSMutableArray new];
    }
    return _beadImages;
}
- (NSMutableArray *)beadAngles{
    if (!_beadAngles){
        _beadAngles = [NSMutableArray new];
    }
    return _beadAngles;
}
-(void)drawRect:(CGRect)rect {
    // 获取图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
 
    //    //绘制路径: 圆形(中心坐标200、200、半径100、起点弧度0、终点弧度2PI、画的方向0逆1正) 第五个参数 是startAngle开始的角度
        CGContextAddArc(ctx, _center_circle.x, _center_circle.y, _radius_circle, 0, M_PI *2, 1);
    //设置空心圆的线条宽度
    CGContextSetLineWidth(ctx, kBorderWith);
    //以矩形rect_circle为依据画一个圆
    CGContextAddEllipseInRect(ctx, rect_circle);
    //填充当前绘画区域的颜色
    [[UIColor greenColor] set];
    //(如果是画圆会沿着矩形外围描画出指定宽度的（圆线）空心圆)/（根据上下文的内容渲染图层）
    CGContextStrokePath(ctx);

}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
    }
    return self;
}
-(void)createView
{
    [self gererateCircleParameters];//生成圆的参数

    [self caculationBeadPoints];//生成圆上念珠的中心点
    [self createImageViews];//放图片上去
    
   
    gestureView = [[UIView alloc]initWithFrame:self.bounds];
    [self addSubview:gestureView];
    gestureView.userInteractionEnabled = YES;
    [self addGestureRecognizer];
    NSLog(@"%lf",asinf(0.5));//求解sin(A) = 0.5 中A的值

    
}
#pragma mark ---- 计算每个珠子的弧度数、中心点等
-(void)caculationBeadPoints{
    angle_average_image = 2 * M_PI / (NSInteger)(2 * M_PI* _radius_circle/image_width);//计算单个图的所占弧度
 
    
    //地点珠子弧度计算 为负数
    CGFloat angle_right_begin =  -(acosf(((2 * _radius_circle - fabs(edgeInsets_circle.left) - self.bounds.size.width) / _radius_circle)) + 2 * angle_average_image) + angle_average_image/4;
  
    //终点珠子弧度计算 d
    CGFloat angle_left_end = M_PI + acosf((_radius_circle - (fabs(edgeInsets_circle.left))) / _radius_circle)  + 4 * angle_average_image;
  
    for (NSUInteger index = 0; index < 100; index++){
        CGFloat angle_index = angle_right_begin + angle_average_image * index;
        [self.beadAngles addObject:@(angle_index)];

        if (angle_index >= angle_left_end){
            angle_index -= angle_average_image;
            [self.beadAngles removeLastObject];
        }
        
    }

    
}
-(void)createImageViews
{
    //圆心
    CGPoint center =  _center_circle;
    //圆半径
    CGFloat radius = _radius_circle;
    //2 初始化视图
    for (NSInteger index = 0; index < self.beadAngles.count; index++) {
        CGFloat angle = [self.beadAngles[index] floatValue];
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, image_width, image_width)];
        imageView.center = CGPointMake(center.x + radius*cos(angle) , center.y + radius * sin(angle));
        [self addSubview:imageView];
        imageView.image = [UIImage imageNamed:@"beads_img1"];
        [self.beadImages addObject:imageView];
    }
}

-(void)gererateCircleParameters{
    CGRect rect = self.bounds;
    edgeInsets_circle = UIEdgeInsetsMake(50, -30, 0, 0);
    CGRect rect_circle = CGRectMake(rect.origin.x + kBorderWith + edgeInsets_circle.left,
                                rect.origin.y+ kBorderWith + edgeInsets_circle.top,
                                rect.size.width* 1.4 - kBorderWith*2,
                                rect.size.height*1.4 - kBorderWith*2);
    _center_circle =  CGPointMake(rect_circle.size.width/2 + rect_circle.origin.x, rect_circle.size.height/2 + rect_circle.origin.y);
    _radius_circle = rect_circle.size.width  * 0.5;
}



#pragma mark ---设置手势
-(void)addGestureRecognizer{
    self.userInteractionEnabled = YES;

    UIPanGestureRecognizer  * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(onPanGesture:)];
    [gestureView addGestureRecognizer:pan];
    pan.delegate = self;
    
   
}

#pragma mark ----  手势回调
-(void)onPanGesture:(UIPanGestureRecognizer *)sender{
    UIGestureRecognizerState state = [sender state];
    CGPoint velocity = [sender velocityInView:sender.view];
    CGPoint translation = [sender translationInView:sender.view];
 
    CGFloat percent = translation.x/ (self.bounds.size.width/3);
    
    //判断移动方向
    if (translation.x>0){
        move_direction_right = YES;
    }
    else{
        move_direction_right = NO;
    }
    if (state == UIGestureRecognizerStateEnded){
        current_percent = percent;
        if (fabs(percent) > 0.33333333333333){//滑动距离超过就0.3333 并且放手直接自动跳转到下个位置
            [self goNextAnimation];
        }
        else{//自动回到初始位置
            [self resetAnimation];
        }
        [sender setTranslation:CGPointZero inView:sender.view];
        return;

    }
    //最多滑动到下一个位置不能继续滑动
    if (fabs(percent)>=1){
        return;
    }
    [self moveBead:percent];


}
//滑动
-(void)moveBead:(CGFloat)percent{
    [self handleNorMalBall:percent];
    [self handleSpecialBall:percent];
    
}
/**
 超过1/3 放开自动跳转到下个
 */
-(void)goNextAnimation{
  
}

/**
 没有超过1/3 放开的话自动恢复到之前的位置
 */
-(void)resetAnimation{
    
  
    
}


//移动普通的球体
-(void)handleNorMalBall:(CGFloat)percent{
    NSInteger index_temp;//根据方向判断滑动起点
    NSInteger end;// for循环终点

    if (move_direction_right){
        index_temp = 0;
        end = self.beadAngles.count - 1;
    }
    else{
        index_temp = 1;
       end =  self.beadAngles.count;
    }
    
    for (NSInteger index = index_temp ; index< end; index++){//循坏移动
 
        
        NSInteger index_begin;
        NSInteger index_next;
        if (move_direction_right){
            index_begin = index;
            index_next = index + 1;
        }
        else{
            index_begin = index;
            index_next = index - 1;
        }
    
        CGFloat angle_begin  =  [self.beadAngles[index_begin] floatValue];
        CGFloat angle_next  =  [self.beadAngles[index_next] floatValue];
        //当前滑动到的弧度
        CGFloat angle = angle_begin + (angle_next - angle_begin) * fabs(percent);
        UIImageView* imageView = self.beadImages[index];
        
        
        imageView.center = CGPointMake(_center_circle.x + _radius_circle*cos(angle) , _center_circle.y + _radius_circle * sin(angle));

    }
    

}
//移动特殊位置的球体、也就是最后一个球体
-(void)handleSpecialBall:(CGFloat)percent{

    NSInteger index_begin;
    NSInteger index_next;
    if (move_direction_right){
        index_begin = self.beadAngles.count - 1;
        index_next = 0;
        
    }
    else{
        index_begin = 0;
        index_next = self.beadAngles.count - 1;
    }
    
    CGFloat angle_begin;
    //note：因为是初始位置、必须加上一个圆周弧度才行。不然会反向移动
    CGFloat angle_next;
    if (move_direction_right){
        angle_begin =  [self.beadAngles[index_begin] floatValue];
        angle_next =  [self.beadAngles[index_next] floatValue] + M_PI * 2;
    }
    else{
        angle_begin =  [self.beadAngles[index_begin] floatValue];
        angle_next =  [self.beadAngles[index_next] floatValue] - M_PI * 2;
    }
   
    //当前滑动到的弧度
    CGFloat angle = angle_begin + (angle_next - angle_begin) * fabs(percent);
    UIImageView* imageView = self.beadImages[index_begin];
    
    
    imageView.center = CGPointMake(_center_circle.x + _radius_circle*cos(angle) , _center_circle.y + _radius_circle * sin(angle));
    
}




@end
